package com.lanou.dllo.soccernews.volley;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.lanou.dllo.soccernews.application.BaseApplication;


public class VolleySingleton {


    private static VolleySingleton instanceSingleton;
    private RequestQueue queue;
    private ImageLoader imageLoader;

    private VolleySingleton() {
        // TODO Auto-generated constructor stub
        queue = getQueue();
        imageLoader = new ImageLoader(queue, new MemoryCache());

    }

    public static VolleySingleton getInstance() {

        if (instanceSingleton == null) {

            synchronized (VolleySingleton.class) {

                if (instanceSingleton == null) {
                    instanceSingleton = new VolleySingleton();
                }

            }

        }
        return instanceSingleton;
    }

    private  RequestQueue getQueue() {
        if (instanceSingleton == null) {
            queue = Volley.newRequestQueue(BaseApplication.getContext());
        }
        return queue;

    }

    public static final String TAG = "VolleySingleton";

    public <T> void addRequest(Request<T> request) {
        request.setTag(TAG);
        queue.add(request);
    }

    public <T> void addRequest(Request<T> request, Object tag) {
        request.setTag(TAG);
        queue.add(request);
    }

    public void removeRequest(Object tag) {
        queue.cancelAll(tag);
    }

    public void addStringRequest(String url, Response.Listener listener,
                                 Response.ErrorListener errorListener) {
        StringRequest request = new StringRequest(url, listener, errorListener);
        addRequest(request);
    }
    public ImageLoader getImageLoader(){
        return imageLoader;
    }
}
